package com.zhongxi.guoyuan.view.rewardCoin;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.RewardCoinPayAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.coinStore.AddressDefaultData;
import com.zhongxi.guoyuan.entity.coinStore.AttrsSelect;
import com.zhongxi.guoyuan.entity.coinStore.CenterToPay;
import com.zhongxi.guoyuan.entity.coinStore.NoPayAddress;
import com.zhongxi.guoyuan.entity.coinStore.PostDefaultAddress;
import com.zhongxi.guoyuan.entity.coinStore.PostGoodPayOrder;
import com.zhongxi.guoyuan.entity.coinStore.PostcartAttrsCollection;
import com.zhongxi.guoyuan.entity.pay.PayAliPayData;
import com.zhongxi.guoyuan.entity.pay.WeixinData;
import com.zhongxi.guoyuan.entity.shopcart.RewardSummary;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.DesTool;
import com.zhongxi.guoyuan.utils.MD5Tool;
import com.zhongxi.guoyuan.view.PaySuccessActivity;
import com.zhongxi.guoyuan.weixin.MD5;
import com.zhongxi.guoyuan.weixin.Util;
import com.zhongxi.guoyuan.widget.sliding.NoScrollListView;
import com.zhongxi.guoyuan.zhifubao.PayResult;
import com.zhongxi.guoyuan.zhifubao.SignUtils;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;

import java.io.StringReader;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class ApplyRewardActivity extends BaseActivity implements View.OnClickListener {

    private TextView tv_reward_price;
    private TextView tv_total_HD;
    private TextView tv_total_MD;
    private TextView tv_total_postage;
    private TextView tv_edit_address;
    private TextView tvUserName;
    private TextView tvAddress;
    private TextView tvPhone;
    private RewardCoinPayAdapter adapter;
    private IWXAPI msgApi;
    private PayReq req;
    private StringBuffer sb;
    private Map<String, String> resultunifiedorder;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();//同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    //判断resultStatus为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        //该笔订单是否真实支付成功，需要依赖服务端的异步通知
                        Intent intent = new Intent(context, PaySuccessActivity.class);
                        intent.putExtra("status", 1);
                        if (goodsList != null && goodsList.size() > 0) {
                            intent.putExtra("md", MD);
                            intent.putExtra("hd", HD);
                        } else {
                            if (1 == attrs.getGoodstype()) {
                                intent.putExtra("md", totalSelfPrice);
                            } else if (3 == attrs.getGoodstype()) {
                                intent.putExtra("hd", totalSelfPrice);
                            }
                        }
                        startActivity(intent);
                    } else {
                        startAct(PaySuccessActivity.class);
                    }
                    break;
            }
        }
    };

    private NoScrollListView listView;
    private ImageView iv_weixin;
    private ImageView iv_zhifubao;
    private RelativeLayout rl_address_info;
    private RelativeLayout relaReceiver;
    private String str = "{";
    private String truetotalPrice = "0.00";
    private String type;
    private String orderId;
    private int index = -1;
    //    private PayParamsResult paramsResult;
    private RewardSummary rewardSummary;
    private AttrsSelect attrs;
    private ArrayList<PostcartAttrsCollection> goodsList;
    private String HD = "0.00";
    private String MD = "0.00";
    private String totalPost = "0";
    private int payType = 0;
    private PayAliPayData aliPayData;
    private WeixinData weixinData;
    private String totalSelfPrice = "0.00";

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_apply_reward);
        initTitle();
        tvTitle.setText("支付确认");
        if (getIntent().getExtras() != null) {
            goodsList = (ArrayList<PostcartAttrsCollection>) getIntent().getExtras().getSerializable("goodsList");
            payType = getIntent().getExtras().getInt("post", 0);     // 1 为邮寄   0 为 自提   2. 同城免邮
        }
        if (getIntent() != null) {
            orderId = getIntent().getStringExtra("orderId");  //个人中心的未支付订单
        }
        if (getIntent() != null) {
            attrs = (AttrsSelect) getIntent().getSerializableExtra("attrs");  //立即支付
            payType = getIntent().getIntExtra("post", 0);    // 1 有邮寄地址  0 无  2. 同城免邮
        }
        tv_edit_address = (TextView) findViewById(R.id.tv_edit_address);
        tvUserName = (TextView) findViewById(R.id.tvUserName);
        tvPhone = (TextView) findViewById(R.id.tvPhone);
        tvAddress = (TextView) findViewById(R.id.tvAddress);
        listView = (NoScrollListView) findViewById(R.id.listView);
        tv_reward_price = (TextView) findViewById(R.id.tv_reward_price);
        tv_total_HD = (TextView) findViewById(R.id.tv_total_HD);
        tv_total_MD = (TextView) findViewById(R.id.tv_total_MD);
        tv_total_postage = (TextView) findViewById(R.id.tv_total_postage);
        iv_weixin = (ImageView) findViewById(R.id.iv_weixin);
        iv_zhifubao = (ImageView) findViewById(R.id.iv_zhifubao);
        rl_address_info = (RelativeLayout) findViewById(R.id.rl_address_info);
        relaReceiver = (RelativeLayout) findViewById(R.id.relaReceiver);
        if (1 == payType || 2 == payType) {
            rl_address_info.setVisibility(View.VISIBLE);
        } else {
            rl_address_info.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initData() {
        super.initData();
        if (goodsList != null && goodsList.size() > 0) {     // 购物车 邮寄
            for (int i = 0; i < goodsList.size(); i++) {
                PostcartAttrsCollection postcartAttrsCollection = goodsList.get(i);
                List<String> list = new ArrayList<>();
                String price = "0.00";
                String singleMD = "0.00";
                String singleHD = "0.00";
                if (orderId != null && !"".equals(orderId)) {   // 个人中心的未支付订单
                    MD = DataUtil.add(MD, postcartAttrsCollection.getTotalMD());
                    HD = DataUtil.add(HD, postcartAttrsCollection.getTotalHD());
                    if (1 == payType) {  //邮寄
                        truetotalPrice = DataUtil.add(truetotalPrice, DataUtil.add(postcartAttrsCollection.getTotalPrice(), postcartAttrsCollection.getPostage()));
                    } else {
                        totalSelfPrice = DataUtil.add(totalSelfPrice, postcartAttrsCollection.getTotalPrice());
                    }
                    totalPost = DataUtil.add(totalPost, postcartAttrsCollection.getPostage());
                } else {
                    String num = "0";
                    for (int j = 0; j < postcartAttrsCollection.getGoodsAttrses().size(); j++) {
                        num = DataUtil.add(num, postcartAttrsCollection.getGoodsAttrses().get(j).getGoodsnum());
                        str += "\"" + postcartAttrsCollection.getGoodsAttrses().get(j).getGoodId() + "\":\"" + postcartAttrsCollection.getGoodsAttrses().get(j).getGoodsnum() + "\",";
                        price = DataUtil.add(price, DataUtil.multiplys(postcartAttrsCollection.getGoodsAttrses().get(j).getPrice(), postcartAttrsCollection.getGoodsAttrses().get(j).getGoodsnum(), 2));
                        list.add(postcartAttrsCollection.getGoodsAttrses().get(j).getPostage());
                        switch (postcartAttrsCollection.getGoodsAttrses().get(j).getGoodstype()) {
                            case "1":
                                singleMD = DataUtil.add(singleMD, DataUtil.multiplys(postcartAttrsCollection.getGoodsAttrses().get(j).getPrice(), postcartAttrsCollection.getGoodsAttrses().get(j).getGoodsnum(), 2));
                                break;
//                            case "2":
//                                MD = DataUtil.add(MD, "0.00");
//                                break;
                            case "3":
                                singleHD = DataUtil.add(singleHD, DataUtil.multiplys(postcartAttrsCollection.getGoodsAttrses().get(j).getPrice(), postcartAttrsCollection.getGoodsAttrses().get(j).getGoodsnum(), 2));
                                break;
                        }
                    }
                    postcartAttrsCollection.getShopInfos().setStoreNum(num);
                    if (postcartAttrsCollection.getShopInfos().getAmountofmail() != null
                            && !"0".equals(postcartAttrsCollection.getShopInfos().getAmountofmail()) && !"".equals(postcartAttrsCollection.getShopInfos().getAmountofmail())) {
                        if (DataUtil.moreThanOther(price, postcartAttrsCollection.getShopInfos().getAmountofmail())) {
                            postcartAttrsCollection.setPostage("0");
                            totalPost = DataUtil.add(totalPost, "0");
                            truetotalPrice = DataUtil.add(truetotalPrice, DataUtil.add(price, "0.00"));  //免邮费
                        } else {
                            postcartAttrsCollection.setPostage(DataUtil.maxString(list));
                            totalPost = DataUtil.add(totalPost, DataUtil.maxString(list));
                            truetotalPrice = DataUtil.add(truetotalPrice, DataUtil.add(price, DataUtil.maxString(list)));
                        }
                    } else {  // 不包邮
                        postcartAttrsCollection.setPostage(DataUtil.maxString(list));  // 一家取最大的邮费
                        totalPost = DataUtil.add(totalPost, DataUtil.maxString(list));
                        truetotalPrice = DataUtil.add(truetotalPrice, DataUtil.add(price, DataUtil.maxString(list)));
                    }
                    totalSelfPrice = DataUtil.add(totalSelfPrice, price);
                    postcartAttrsCollection.setTotalPrice(price);
                    postcartAttrsCollection.setTotalMD(singleMD);
                    postcartAttrsCollection.setTotalHD(singleHD);
                }
                MD = DataUtil.add(MD, singleMD);
                HD = DataUtil.add(HD, singleHD);
            }
            if (DataUtil.moreThanZero(HD) && DataUtil.moreThanZero(MD)) {
                tv_total_HD.setVisibility(View.VISIBLE);
                tv_total_MD.setVisibility(View.VISIBLE);
                tv_total_HD.setText(context.getResources().getString(R.string.award_hongdou) + HD + "红豆/");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    tv_total_MD.setText(Html.fromHtml(context.getResources().getString(R.string.give_meidou) + "<font color='#ff7f00'>"
                            + CommonTool.getWhole(MD) + "美豆</font><font color='#ff4c4c'>/"+context.getResources().getString(R.string.more_give) + DataUtil.multiplys(MD, "0.05", 2) + "红豆</font>", Html.FROM_HTML_MODE_COMPACT));
                } else {
                    tv_total_MD.setText(Html.fromHtml(context.getResources().getString(R.string.give_meidou) + "<font color='#ff7f00'>"
                            + CommonTool.getWhole(MD) + "美豆</font><font color='#ff4c4c'>/"+context.getResources().getString(R.string.more_give) + DataUtil.multiplys(MD, "0.05", 2) + "红豆</font>"));
                }
            } else if (DataUtil.moreThanZero(HD) && !DataUtil.moreThanZero(MD)) {
                tv_total_HD.setVisibility(View.VISIBLE);
                tv_total_MD.setVisibility(View.GONE);
                tv_total_HD.setText(context.getResources().getString(R.string.award_hongdou) + HD + "红豆");
            } else if (!DataUtil.moreThanZero(HD) && DataUtil.moreThanZero(MD)) {
                tv_total_HD.setVisibility(View.GONE);
                tv_total_MD.setVisibility(View.VISIBLE);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    tv_total_MD.setText(Html.fromHtml(context.getResources().getString(R.string.give_meidou) + "<font color='#ff7f00'>"
                            + CommonTool.getWhole(MD) + "美豆</font><font color='#ff4c4c'>/"+context.getResources().getString(R.string.more_give) + DataUtil.multiplys(MD, "0.05", 2) + "红豆</font>", Html.FROM_HTML_MODE_COMPACT));
                } else {
                    tv_total_MD.setText(Html.fromHtml(context.getResources().getString(R.string.give_meidou) + "<font color='#ff7f00'>"
                            + CommonTool.getWhole(MD) + "美豆</font><font color='#ff4c4c'>/"+context.getResources().getString(R.string.more_give) + DataUtil.multiplys(MD, "0.05", 2) + "红豆</font>"));
                }
            } else {
                tv_total_HD.setVisibility(View.GONE);
                tv_total_MD.setVisibility(View.GONE);
            }
            if (1 == payType) {
                tv_reward_price.setText(truetotalPrice + " 元");
                tv_total_postage.setText("快递: " + totalPost + " 元");
            } else {
                tv_reward_price.setText(totalSelfPrice + " 元");
                tv_total_postage.setText("");
            }
        } else {
            if (1 == payType) {
                if (null != attrs.getAmountofmail() && !"".equals(attrs.getAmountofmail()) && !"0".equals(attrs.getAmountofmail())) {
                    if (DataUtil.moreThanOther(DataUtil.multiplys(attrs.getPrice(), attrs.getGoodsnum(), 2), attrs.getAmountofmail())) {
                        tv_total_postage.setText("快递: 0 元");
                        tv_reward_price.setText(DataUtil.multiplys(attrs.getPrice(), attrs.getGoodsnum(), 2) + " 元");
                    } else {
                        tv_total_postage.setText("快递: " + attrs.getPostage() + " 元");
                        tv_reward_price.setText(DataUtil.add(DataUtil.multiplys(attrs.getPrice(), attrs.getGoodsnum(), 2), attrs.getPostage()) + " 元");
                    }
                } else {
                    tv_total_postage.setText("快递: " + attrs.getPostage() + " 元");
                    tv_reward_price.setText(DataUtil.add(DataUtil.multiplys(attrs.getPrice(), attrs.getGoodsnum(), 2), attrs.getPostage()) + " 元");
                }
            } else {
                tv_reward_price.setText(DataUtil.multiplys(attrs.getPrice(), attrs.getGoodsnum(), 2) + " 元");
                tv_total_postage.setText("");
            }
            totalSelfPrice = DataUtil.multiplys(attrs.getPrice(), attrs.getGoodsnum(), 2);
            switch (attrs.getGoodstype()) {
                case 1:  //美豆
                    tv_total_HD.setVisibility(View.GONE);
                    tv_total_MD.setVisibility(View.VISIBLE);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        tv_total_MD.setText(Html.fromHtml(context.getResources().getString(R.string.give_meidou) + "<font color='#ff7f00'>" + CommonTool.getWhole(totalSelfPrice)
                                + "美豆</font><font color='#ff4c4c'>/"+context.getResources().getString(R.string.more_give) + DataUtil.multiplys(totalSelfPrice, "0.05", 2) + "红豆</font>", Html.FROM_HTML_MODE_COMPACT));
                    } else {
                        tv_total_MD.setText(Html.fromHtml(context.getResources().getString(R.string.give_meidou) + "<font color='#ff7f00'>" + CommonTool.getWhole(totalSelfPrice)
                                + "美豆</font><font color='#ff4c4c'>/" +context.getResources().getString(R.string.more_give)+ DataUtil.multiplys(totalSelfPrice, "0.05", 2) + "红豆</font>"));
                    }
                    break;
                case 3:  //红豆
                    tv_total_HD.setVisibility(View.VISIBLE);
                    tv_total_MD.setVisibility(View.GONE);
                    tv_total_HD.setText(context.getResources().getString(R.string.award_hongdou) + totalSelfPrice + "红豆");
                    break;
            }
        }
        adapter = new RewardCoinPayAdapter(this, goodsList, attrs, payType);
        listView.setAdapter(adapter);
        getAddressInfo();
    }

    private void getAddressInfo() {
        if (orderId != null && !"".equals(orderId)) {
            PostcartAttrsCollection postcartAttrsCollection = goodsList.get(0);
            if (null != postcartAttrsCollection.getAddress() && !"".equals(postcartAttrsCollection.getAddress())) {
                NoPayAddress address = postcartAttrsCollection.getAddress();
                relaReceiver.setVisibility(View.VISIBLE);
                tvUserName.setText(address.getName());
                tvPhone.setText(address.getPhone());
                tvAddress.setText(address.getAddress());
            } else {
                getPresonIfo();
            }
        } else {
            getPresonIfo();
        }
    }

    private void getPresonIfo() {
        if (TextUtils.isEmpty(MyApplication.getInstance().getRewardAddressid())) {
            relaReceiver.setVisibility(View.GONE);
            getDefaultAddress();
        } else {
            relaReceiver.setVisibility(View.VISIBLE);
            tvUserName.setText(MyApplication.getInstance().getRewardName());
            tvPhone.setText(MyApplication.getInstance().getRewardUserPhone());
            tvAddress.setText(MyApplication.getInstance().getRewardAddress());
        }
    }

    private void getDefaultAddress() {
        type = "defaultAddress";
        getServer(Url.REWARD_DEFAULT_ADDRESS, null, "", false, null, "get");
    }

    /**
     * 解析后台返回的支付商户信息
     *
     * @param securityKey
     */
    private String parseSecutiryKey(String securityKey) {
        String jsonStr = "";
        try {
            String sourcestr = MD5Tool.Md5(MyApplication.getInstance().getSk() + MyApplication.getInstance().getNow());
            String strs = URLDecoder.decode(securityKey, "UTF-8");
            jsonStr = DesTool.splitdecode(sourcestr, strs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonStr;
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        tv_edit_address.setOnClickListener(this);
        iv_weixin.setOnClickListener(this);
        iv_zhifubao.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.tv_edit_address:
                Intent intent = new Intent(context, RewardAddressListActivity.class);
                startActivityForResult(intent, 100);
                break;
            case R.id.iv_weixin:
                if (CommonTool.isFirstLongScroll()) {
                    index = 0;
                    if (goodsList != null && goodsList.size() > 0) {
                        if (orderId != null && !"".equals(orderId)) {     //个人中心的未支付的订单支付
                            toPay();
                        } else {           //购物车来的支付
                            if (1 == payType || 2 == payType) {  //邮寄
                                if ("".equals(MyApplication.getInstance().getRewardAddressid())) {
                                    showShortToast("请选择邮寄地址");
                                } else {
                                    getOrderList();
                                }
                            } else {   // 自提
                                getOrderList();
                            }
                        }
                    } else {                            //商品详情直接来的立即支付
                        if (1 == payType || 2 == payType) {  //邮寄
                            if ("".equals(MyApplication.getInstance().getRewardAddressid())) {
                                showShortToast("请选择邮寄地址");
                            } else {
                                rightNowPay();
                            }
                        } else {
                            rightNowPay();
                        }
                    }
                }
                break;
            case R.id.iv_zhifubao:
                if (CommonTool.isFirstLongScroll()) {
                    index = 1;
                    if (goodsList != null && goodsList.size() > 0) {
                        if (orderId != null && !"".equals(orderId)) {     //个人中心的未支付的订单支付
                            toPay();
                        } else {           //购物车来的支付
                            if (1 == payType || 2 == payType) {  //邮寄
                                if ("".equals(MyApplication.getInstance().getRewardAddressid())) {
                                    showShortToast("请选择邮寄地址");
                                } else {
                                    getOrderList();
                                }
                            } else {
                                getOrderList();
                            }
                        }
                    } else {                            //商品详情直接来的立即支付
                        if (1 == payType || 2 == payType) {  //邮寄
                            if ("".equals(MyApplication.getInstance().getRewardAddressid())) {
                                showShortToast("请选择邮寄地址");
                            } else {
                                rightNowPay();
                            }
                        } else {
                            rightNowPay();
                        }
                    }
                }
                break;
        }
    }

    private void toPay() {
        type = "fromCenter";
        String strs = "&orderid=" + orderId;
        getServer(Url.REWARD_TO_PAY, null, strs, false, null, "get");
    }

    private void getOrderList() {
        Map<String, String> map = new HashMap<>();
        type = "topay";
        String remark = "{";
        for (int i = 0; i < goodsList.size(); i++) {
            if (TextUtils.isEmpty(goodsList.get(i).getCustomNotes())) {
                remark = remark + goodsList.get(i).getShopInfos().getId() + ":,";
            }else {
                remark = remark + goodsList.get(i).getShopInfos().getId() + ":" + goodsList.get(i).getCustomNotes() + ",";
            }
        }
        if (1 == payType) {   //  邮寄
            map.put("shippingid", MyApplication.getInstance().getRewardAddressid());
            map.put("totalpostage", totalPost);
            map.put("postRemark", remark.substring(0, remark.length() - 1) + "}");
        } else if (2 == payType) {   //同城
            map.put("shippingid", MyApplication.getInstance().getRewardAddressid());
            map.put("localRemark", remark.substring(0, remark.length() - 1) + "}");
        } else {
            map.put("todoorRemark", remark.substring(0, remark.length() - 1) + "}");
        }
        map.put("shopcartInfo", str.substring(0, str.length() - 1) + "}");
        map.put("totalAmout", totalSelfPrice);
        getServer(Url.REWARD_SHOPPING_PAY_ORDER, map, "", false, null, "post");
    }

    private void rightNowPay() {
        type = "topay";
        Map<String, String> map = new HashMap<>();
        map.put("shopid", attrs.getShopId());
        map.put("goodsid", attrs.getGoodsid());
        map.put("goodsnum", attrs.getGoodsnum());
        map.put("collectionid", attrs.getId());
        map.put("attrlist", attrs.getAttrlist());
        if (!TextUtils.isEmpty(attrs.getCustomNotes())) {
            map.put("remark", attrs.getCustomNotes());
        }
        if (1 == payType) {
            map.put("shippingid", MyApplication.getInstance().getRewardAddressid());
            map.put("getermethod", "1");
        } else if (2 == payType) {
            map.put("shippingid", MyApplication.getInstance().getRewardAddressid());
            map.put("getermethod", "4");
        } else {
            map.put("getermethod", "2");
        }
        getServer(Url.REWARD_SHOPPING_PAY_REIGHTNOW, map, "", false, null, "post");
    }

    @Override
    protected void processSuccessResult(String response) throws JSONException {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if ("defaultAddress".equals(type)) {
                PostDefaultAddress defaultAddress = gson.fromJson(response, PostDefaultAddress.class);
                MyApplication.getInstance().setSpValue(defaultAddress.getSafeobj());
                if (defaultAddress.getData() != null && !"".equals(defaultAddress.getData())) {
                    AddressDefaultData data = defaultAddress.getData();
                    if (data.getId() != null && !"".equals(data.getId())) {
                        relaReceiver.setVisibility(View.VISIBLE);
                        String addressId = data.getId();
                        MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddressid", addressId).commit();
                        String address = "";
                        if (data.getProvince() != null && !"".equals(data.getProvince())) {
                            address += data.getProvince();
                        }
                        if (data.getCity() != null && !"".equals(data.getCity())) {
                            address += data.getCity();
                        }
                        if (data.getPrefecture() != null && !"".equals(data.getPrefecture())) {
                            address += data.getPrefecture();
                        }
                        if (data.getAddress() != null && !"".equals(data.getAddress())) {
                            address += data.getAddress();
                        }
                        tvAddress.setText("地址:" + address);
                        MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddress", address).commit();
                        if (data.getUsername() != null && !"".equals(data.getUsername())) {
                            tvUserName.setText(data.getUsername());
                            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardName", data.getUsername()).commit();
                        }
                        if (data.getMphone() != null && !"".equals(data.getMphone())) {
                            tvPhone.setText(data.getMphone());
                            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardUserphone", data.getMphone()).commit();
                        }
                    } else {
                        relaReceiver.setVisibility(View.GONE);
                    }
                } else {
                    relaReceiver.setVisibility(View.GONE);
                }
            } else if ("topay".equals(type)) {
                PostGoodPayOrder postGoodPayOrder = gson.fromJson(response, PostGoodPayOrder.class);
                MyApplication.getInstance().setSpValue(postGoodPayOrder.getSafeobj());
                JSONObject baseObject = new JSONObject(response);
                if (goodsList != null && goodsList.size() > 0) {
                    JSONArray jsonArray = baseObject.optJSONArray("orderid");
                    if (jsonArray != null && jsonArray.length() > 0) {
                        String str = "";
                        for (int i = 0; i < jsonArray.length(); i++) {
                            str += jsonArray.get(i) + ",";
                        }
                        orderId = str.substring(0, str.length() - 1);
                    }
                } else {
                    orderId = baseObject.optString("orderid");
                }

                if (postGoodPayOrder.getSecurityKey() != null && !"".equals(postGoodPayOrder.getSecurityKey())) {
                    String payParams = parseSecutiryKey(postGoodPayOrder.getSecurityKey());
                    JSONObject jsonObject = new JSONObject(payParams);
                    JSONObject alipay = jsonObject.optJSONObject("alipay");
                    aliPayData = PayAliPayData.parseObject(alipay);
                    JSONObject wechat = jsonObject.optJSONObject("wechat");
                    weixinData = WeixinData.parseObject(wechat);
//                    paramsResult = gson.fromJson(payParams, PayParamsResult.class);
                }
                if (null != postGoodPayOrder.getSummary() && !"".equals(postGoodPayOrder.getSummary())) {
                    String summary = MyApplication.getInstance().parseSecutiryKey(postGoodPayOrder.getSummary());
                    JSONObject object = new JSONObject(summary);
                    rewardSummary = RewardSummary.parseObject(object);
//                    rewardSummary = gson.fromJson(summary, RewardSummary.class);
                }
                MyApplication.getInstance().sharedPrefrences.edit().putString("pay", "reward").commit();
                if (index == 0) {//微信支付
                    if (goodsList != null && goodsList.size() > 0) {
                        MyApplication.getInstance().sharedPrefrences.edit().putString("weixinMD", MD).commit();
                        MyApplication.getInstance().sharedPrefrences.edit().putString("weixinHD", HD).commit();
                    } else {
                        if (1 == attrs.getGoodstype()) {
                            MyApplication.getInstance().sharedPrefrences.edit().putString("weixinMD", totalSelfPrice).commit();
                            MyApplication.getInstance().sharedPrefrences.edit().putString("weixinHD", "0.00").commit();
                        } else if (3 == attrs.getGoodstype()) {
                            MyApplication.getInstance().sharedPrefrences.edit().putString("weixinMD", "0.00").commit();
                            MyApplication.getInstance().sharedPrefrences.edit().putString("weixinHD", totalSelfPrice).commit();
                        } else {
                            MyApplication.getInstance().sharedPrefrences.edit().putString("weixinMD", "0.00").commit();
                            MyApplication.getInstance().sharedPrefrences.edit().putString("weixinHD", "0.00").commit();
                        }
                    }
                    weixinPay(weixinData);
                } else if (index == 1) {//支付宝支付
                    zhifubaoPay(aliPayData);
                }
            } else if ("fromCenter".equals(type)) {
                CenterToPay centerToPay = gson.fromJson(response, CenterToPay.class);
                MyApplication.getInstance().setSpValue(centerToPay.getSafeobj());
                if (centerToPay.getSecurityKey() != null && !"".equals(centerToPay.getSecurityKey())) {
                    String payParams = parseSecutiryKey(centerToPay.getSecurityKey());
                    JSONObject jsonObject = new JSONObject(payParams);
                    JSONObject alipay = jsonObject.optJSONObject("alipay");
                    aliPayData = PayAliPayData.parseObject(alipay);
                    JSONObject wechat = jsonObject.optJSONObject("wechat");
                    weixinData = WeixinData.parseObject(wechat);
                }
                rewardSummary = new RewardSummary();
                if (1 == payType) {
                    rewardSummary.setPostage(centerToPay.getOrderInfo().getPostage());
                } else {
                    rewardSummary.setPostage("0");
                }
                rewardSummary.setAmount(DataUtil.add(centerToPay.getOrderInfo().getShouldprice(), centerToPay.getOrderInfo().getPostage()));

                MyApplication.getInstance().sharedPrefrences.edit().putString("pay", "reward").commit();
                if (index == 0) {//微信支付
                    MyApplication.getInstance().sharedPrefrences.edit().putString("weixinMD", MD).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("weixinHD", HD).commit();
                    weixinPay(weixinData);
                } else if (index == 1) {//支付宝支付
                    zhifubaoPay(aliPayData);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
            if (1000 == result.getCode()) {
                showShortToast("参数错误");
            } else if (1557 == result.getCode()) {
                showShortToast("数量超限");
            } else if (2001 == result.getCode()) {
                showShortToast("库存不足");
            } else if (2005 == result.getCode()) {
                showShortToast("商品与 商品集合不匹配");
            } else if (2006 == result.getCode()) {
                showShortToast("商品集合数据格式错误");  //商品集合数据格式错误
            } else if (2007 == result.getCode()) {
                showShortToast("商品属性不在指定集合中");
            } else if (2008 == result.getCode()) {
                showShortToast("商品属性数据丢失， 请管理员调整");
            } else if (2009 == result.getCode()) {
                showShortToast("商品属性选择不完整");
            } else if (2013 == result.getCode()) {
                showShortToast("邮费错误");
            } else if (2015 == result.getCode()) {
                showShortToast("订单镜像丢失");
            } else if (2016 == result.getCode()) {
                showShortToast("订单定制信息已丢失");
            } else if (5019 == result.getCode()) {
                showShortToast("选购商品数量超过库存");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 支付宝支付
     *
     * @param alipay
     */
    private void zhifubaoPay(PayAliPayData alipay) {

        String orderInfo = getOrderInfo(alipay);
        /**
         * 特别注意，这里的签名逻辑需要放在服务端，切勿将私钥泄露在代码中
         */
        String sign = sign(orderInfo, alipay.getRsaPrivate());
        try {
            /**
             * 仅需对sign做URL编码
             */
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        /**
         * 完整的符合支付宝参数规范的订单信息
         */
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType();

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(ApplyRewardActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);

                Message msg = new Message();
                msg.what = 0;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();

    }

    private String genOutTradNo() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }

    /**
     * create the order info. 创建订单信息（支付宝）
     */
    private String getOrderInfo(PayAliPayData alipay) {
        String trade = "";
        if ((orderId + genOutTradNo()).length() > 32) {
            trade = (orderId + genOutTradNo()).substring(0, 32);
        } else {
            trade = orderId + genOutTradNo();
        }

        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + alipay.getPartner() + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + alipay.getSeller() + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + trade + "\"";
        if (goodsList != null && goodsList.size() > 0) { // 商品名称
            if (goodsList.size() > 1) {
                orderInfo += "&subject=" + "\"" + goodsList.get(0).getGoodsAttrses().get(0).getName() + "..." + "\"";
            } else {
                orderInfo += "&subject=" + "\"" + goodsList.get(0).getGoodsAttrses().get(0).getName() + "\"";
            }
        } else {
            orderInfo += "&subject=" + "\"" + attrs.getName() + "\"";
        }
        // 商品详情
        orderInfo += "&body=" + "\"" + getTimeValue() + "||" + MyApplication.getInstance().getUserId() + "||"
                + orderId + "||3||" + DataUtil.formatData(rewardSummary.getPostage()) + "," + DataUtil.formatData(rewardSummary.getAmount()) + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + DataUtil.formatData(rewardSummary.getAmount()) + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + Url.BASE_URL + "/notify/pay/alipay" + "\"";

        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        orderInfo += "&return_url=\"" + Url.BASE_URL + "\"";
        return orderInfo;
    }

    /**
     * sign the order info. 对订单信息进行签名（支付宝）
     *
     * @param content 待签名订单信息
     */
    private String sign(String content, String rsa_private) {
        return SignUtils.sign(content, rsa_private);
    }

    /**
     * get the sign type we use. 获取签名方式（支付宝）
     */
    private String getSignType() {
        return "sign_type=\"RSA\"";
    }

    /**
     * 微信支付
     *
     * @param wechat
     */
    private void weixinPay(WeixinData wechat) {
        msgApi = WXAPIFactory.createWXAPI(this, wechat.getAppid());
        // 将该app注册到微信
        msgApi.registerApp(wechat.getAppid());
        getWXOrderInfo();
    }

    /**
     * 获取微信支付订单
     */
    private void getWXOrderInfo() {
        //正常情况下，请求服务器获取订单参数
        req = new PayReq();
        sb = new StringBuffer();
        GetPrepayIdTask getPrepayId = new GetPrepayIdTask();
        getPrepayId.execute();
    }

    private class GetPrepayIdTask extends AsyncTask<Void, Void, Map<String, String>> {

        private ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            dialog = ProgressDialog.show(context, getString(R.string.app_tip), getString(R.string.getting_prepayid));
        }

        @Override
        protected void onPostExecute(Map<String, String> result) {
            if (dialog != null) {
                dialog.dismiss();
            }
            sb.append("prepay_id\n" + result.get("prepay_id") + "\n\n");
            resultunifiedorder = result;
            genPayReq();
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @Override
        protected Map<String, String> doInBackground(Void... params) {

            String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
            String entity = genProductArgs();

            Log.e("orion", entity);

            byte[] buf = Util.httpPost(url, entity);

            String content = new String(buf);
            Log.e("orion", content);
            Map<String, String> xml = decodeXml(content);

            return xml;
        }

    }

    private void genPayReq() {

        req.appId = weixinData.getAppid();
        req.partnerId = weixinData.getSeller();
        req.prepayId = resultunifiedorder.get("prepay_id");
        req.packageValue = "Sign=WXPay";
        req.nonceStr = genNonceStr();
        req.timeStamp = String.valueOf(genTimeStamp());


        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        signParams.add(new BasicNameValuePair("appid", req.appId));
        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
        signParams.add(new BasicNameValuePair("package", req.packageValue));
        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));

        req.sign = genAppSign(signParams);

        sb.append("sign\n" + req.sign + "\n\n");

        msgApi.sendReq(req);

    }

    private String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(weixinData.getPartner());

        this.sb.append("sign str\n" + sb.toString() + "\n\n");
        String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        Log.e("orion", appSign);
        return appSign;
    }


    @Nullable
    private String genProductArgs() {
        StringBuffer xml = new StringBuffer();
        try {
            String nonceStr = genNonceStr();
            String trade = "";
            if ((orderId + genOutTradNo()).length() > 32) {
                trade = (orderId + genOutTradNo()).substring(0, 32);
            } else {
                trade = orderId + genOutTradNo();
            }
            trade = trade.replace(",", "");
            xml.append("</xml>");
            List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
            packageParams.add(new BasicNameValuePair("appid", weixinData.getAppid()));
            packageParams.add(new BasicNameValuePair("attach", getTimeValue() + "||" + MyApplication.getInstance().getUserId() + "||"
                    + orderId + "||3||" + DataUtil.formatData(rewardSummary.getPostage()) + "," + DataUtil.formatData(rewardSummary.getAmount())));
            if (goodsList != null && goodsList.size() > 0) {
                if (goodsList.size() > 1) {
                    packageParams.add(new BasicNameValuePair("body", goodsList.get(0).getGoodsAttrses().get(0).getName() + "..."));
                } else {
                    packageParams.add(new BasicNameValuePair("body", goodsList.get(0).getGoodsAttrses().get(0).getName()));
                }
            } else {
                packageParams.add(new BasicNameValuePair("body", attrs.getName()));
            }
            packageParams.add(new BasicNameValuePair("mch_id", weixinData.getSeller()));
            packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
            packageParams.add(new BasicNameValuePair("notify_url", Url.BASE_URL + "/notify/pay/wepay"));
            packageParams.add(new BasicNameValuePair("out_trade_no", trade));
            packageParams.add(new BasicNameValuePair("spbill_create_ip", MyApplication.getInstance().getLocalIPAddress()));
            packageParams.add(new BasicNameValuePair("total_fee", new BigDecimal(rewardSummary.getAmount()).multiply(new BigDecimal(100)).intValue() + ""));
            packageParams.add(new BasicNameValuePair("trade_type", "APP"));

            String sign = genPackageSign(packageParams);
            packageParams.add(new BasicNameValuePair("sign", sign));

            String xmlstring = toXml(packageParams);

            Log.i("base", xmlstring);
            return new String(xmlstring.toString().getBytes(), "ISO8859-1");

        } catch (Exception e) {
            Log.e("base", "" + e.getMessage());
            return null;
        }
    }

    private String toXml(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        for (int i = 0; i < params.size(); i++) {
            sb.append("<" + params.get(i).getName() + ">");


            sb.append(params.get(i).getValue());
            sb.append("</" + params.get(i).getName() + ">");
        }
        sb.append("</xml>");

        Log.e("orion", sb.toString());
        return sb.toString();
    }

    public Map<String, String> decodeXml(String content) {
        try {
            Map<String, String> xml = new HashMap<String, String>();
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(new StringReader(content));
            int event = parser.getEventType();
            while (event != XmlPullParser.END_DOCUMENT) {

                String nodeName = parser.getName();
                switch (event) {
                    case XmlPullParser.START_DOCUMENT:

                        break;
                    case XmlPullParser.START_TAG:

                        if ("xml".equals(nodeName) == false) {
                            //实例化student对象
                            xml.put(nodeName, parser.nextText());
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                }
                event = parser.next();
            }

            return xml;
        } catch (Exception e) {
            Log.e("orion", e.toString());
        }
        return null;

    }

    private String genNonceStr() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }

    private long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 生成签名（微信）
     */

    private String genPackageSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(weixinData.getPartner());

        String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        Log.e("orion", packageSign);
        return packageSign;
    }

    /**
     * 获取当前时间戳
     *
     * @return
     */
    private String getTimeValue() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String str = sdf.format(date);
        return str;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && resultCode == 0) {
            getPresonIfo();
        } else if (requestCode == 100 && resultCode == RewardAddressListActivity.RESULTCODEADDRESS) {
            if (null != MyApplication.getInstance().getRewardAddressid() && !"".equals(MyApplication.getInstance().getRewardAddressid())) {
                relaReceiver.setVisibility(View.VISIBLE);
                tvUserName.setText(MyApplication.getInstance().getRewardName());
                tvPhone.setText(MyApplication.getInstance().getRewardUserPhone());
                tvAddress.setText(MyApplication.getInstance().getRewardAddress());
            } else {
                relaReceiver.setVisibility(View.GONE);
            }
        } else if (requestCode == adapter.REQUESTNOTESCODE && resultCode == CustomerNotesActivity.RESULTNOTESCODE) {
            String mNotes = data.getStringExtra("notes");
            String mShopid = data.getStringExtra("shopid");
            if (goodsList != null && goodsList.size() > 0) {
                for (int i = 0; i < goodsList.size(); i++) {
                    if (goodsList.get(i).getShopInfos().getId().equals(mShopid)) {
                        goodsList.get(i).setCustomNotes(mNotes);
                    }
                }
            } else {
                if (attrs.getShopId().equals(mShopid)) {
                    attrs.setCustomNotes(mNotes);
                }
            }
            adapter.notifyDataSetChanged();
        }
    }
}
